﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace SentientGrid
{
    public static class SentientGrid
    {
        public static MvcHtmlString SGridFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string url, IDictionary<string, object> gridParameters = null)
        {

            /*
             * Build a jqGrid based on the field names and the columns in an MVC model.
             */

            var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            var type = metadata.ModelType;

            // Right now we only know how to deal with collections
            if (type.IsGenericType)
            {
                type = type.GetGenericArguments()[0];
                var id = ExpressionHelper.GetExpressionText(expression);
                var label = metadata.DisplayName;

                var gb = new GridBuilder(id, label, type, url, metadata, gridParameters);
                var output = new StringBuilder(string.Format("<table id=\"{0}\">\r\n</table>", id));
                output.Append(gb.BuildJQGrid());

                return MvcHtmlString.Create(output.ToString());
            }

            return MvcHtmlString.Create(string.Empty);
        }

        public static MvcHtmlString SGrid(this HtmlHelper helper, string id, Type type, string url, string label = null, IDictionary<string, object> gridParameters = null)
        {

            // Right now we only know how to deal with collections
            if (type.IsGenericType)
            {
                type = type.GetGenericArguments()[0];
            }

            var gb = new GridBuilder(id, label, type, url, null, gridParameters);
            var output = new StringBuilder(string.Format("<table id=\"{0}\">\r\n</table>", id));
            output.Append(gb.BuildJQGrid());

            return MvcHtmlString.Create(output.ToString());
        }

        public static MvcHtmlString SGrid(this HtmlHelper helper, string id, Type type, string url, string label = null, object gridParameters = null)
        {
            var gType = gridParameters.GetType();
            var props = gType.GetProperties();
            var dictionary = new Dictionary<string, object>();

            foreach (var i in props)
            {
                dictionary.Add(i.Name, i.GetValue(gridParameters, null));
            }

            return SGrid(helper, id, type, url, label, dictionary);

        }

        public static MvcHtmlString SGrid(this HtmlHelper helper, string id, Type type, string url, string label = null)
        {
            return SGrid(helper, id, type, url, label, (null as IDictionary<string, object>));
        }
    }
}
